package com.csp.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.csp.app.common.ChatServer;
import com.csp.app.common.Const;
import com.csp.app.common.ResponseBuilder;
import com.csp.app.entity.Friend;
import com.csp.app.entity.User;
import com.csp.app.service.RedisService;
import com.csp.app.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

@RestController
public class ServiceController {
    public static final String IMG_DIR = "/var/img/";
    private final static Logger logger = LoggerFactory.getLogger(ServiceController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private ChatServer chatServer;
    @Autowired
    private RedisService redisService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseBuilder login(User user, HttpSession session) {
        try {
            User checkUser = userService.login(user);
            if (checkUser != null) {
                session.setAttribute("user", checkUser);
                return ResponseBuilder.buildSuccess(checkUser);
            } else {
                return ResponseBuilder.buildFail("账号或者密码错误");
            }
        } catch (Exception e) {
            logger.error("login error:{}", e);
        }
        return ResponseBuilder.buildError();
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseBuilder register(User user) {
        try {
            userService.register(user);
            return ResponseBuilder.buildSuccess(user);
        } catch (Exception e) {
            logger.error("register error:{}", e);
        }
        return ResponseBuilder.buildError();
    }

    @RequestMapping("/inside/searchFriend")
    public ResponseBuilder searchFriend(User user) {
        try {
            List<User> users = userService.searchFriend(user);
            return ResponseBuilder.buildSuccess(users);
        } catch (Exception e) {
            logger.error("searchFriend error:{}", e);
        }
        return ResponseBuilder.buildError();
    }

    @RequestMapping(value = "/inside/addFriend", method = RequestMethod.POST)
    public ResponseBuilder addFriend(Long friendId, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            Friend friend = new Friend();
            friend.setId(user.getId());
            friend.setFriendId(friendId);
            User addedFriend = userService.addFriend(friend);
            /*
            Session socketSession = chatServer.getSessionById(friendId);
            String key = String.format(Const.USER_ID_USER, friendId);
            JSONObject object = redisService.getObject(key, Const.DEFAULT_INDEX, JSONObject.class);
            object.put("groupid", 1);
            object.put("type", "friend");
            object.put("emit", "addFriend");
            if (socketSession != null) {
                socketSession.getBasicRemote().sendText(object.toJSONString());
            } else {
                key = String.format(Const.OFFLINE_ADD_FRIEND, friendId);
                redisService.rpushObject(key,object);
            }*/
            return ResponseBuilder.buildSuccess("已添加该好友",addedFriend);
        } catch (Exception e) {
            logger.error("addFriend error:{}", e);
        }
        return ResponseBuilder.buildError();
    }

    @RequestMapping("/inside/init")
    public ResponseBuilder init(HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            JSONObject initData = new JSONObject();
            initData.put("mine", user);
            List<User> addFriends = userService.selectAddedFriendById(user.getId());
            JSONObject friends = new JSONObject();
            friends.put("groupname", "friend");
            friends.put("id", "1");
            friends.put("list", addFriends);
            initData.put("friend", new Object[]{friends});
            return ResponseBuilder.buildSuccess(initData);
        } catch (Exception e) {
            logger.error("init error:{}", e);
        }
        return ResponseBuilder.buildError();
    }

    @RequestMapping("/inside/avatar/{imgName}")
    public void getAvatar(@PathVariable("imgName") String imgName, HttpSession session, HttpServletResponse response) {
        FileInputStream fis = null;
        ServletOutputStream outputStream = null;
        try {
            File imgFile;
            if (StringUtils.isNotEmpty(imgName)) {
                outputStream = response.getOutputStream();
                User user = (User) session.getAttribute("user");
                imgFile = new File(IMG_DIR + user.getId() + "/" + imgName);
                if (!imgFile.exists()) {
                    imgFile = new File("/var/img/356.jpg");
                }

            } else {
                imgFile = new File("/var/img/356.jpg");
            }
            fis = new FileInputStream(imgFile);
            byte[] b = new byte[1024];
            while ((fis.read(b)) != -1) {
                outputStream.write(b);
            }
        } catch (IOException e) {
            logger.error("{}", e);
        } catch (Exception e) {
            logger.error("{}", e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping(value = "/inside/updateUser", method = RequestMethod.POST)
    public ResponseBuilder updateUser(User user) {
        try {
            boolean b = userService.updateById(user);
            if (b) {
                return ResponseBuilder.buildSuccess(null);
            } else {
                return ResponseBuilder.buildFail("失败");
            }
        } catch (Exception e) {
            logger.error("updateUser error:{}", e);
        }
        return ResponseBuilder.buildError();
    }
}
